from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group

#1,管理员的序列化器
class PermissionAdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

    #1,重写create方法,目的加密密码,和设置管理员
    def create(self, validated_data):

        #1,添加管理员的属性
        validated_data["is_superuser"] = True
        validated_data["is_staff"] = True

        #2,创建管理员
        user = super().create(validated_data)

        #3,密码加密
        user.set_password(validated_data["password"])
        user.save()

        return user

    #2,重写update方法,密码加密处理
    def update(self, instance, validated_data):

        #1,调用系统方法更新数据
        instance = super().update(instance,validated_data)

        #2,加密密码
        instance.set_password(validated_data["password"])
        instance.save()

        #3,返回
        return instance


#2,组信息的序列化器
class PermissionGroupSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ("id","name")